from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, HttpResponseForbidden
import re
from .models import User

# Create your views here.

class RegisterView(View):
    """用户注册视图"""

    def get(self, request):
        return render(request, "register.html")

    def post(self, request):
        """实现用户注册逻辑"""
        # 接收参数
        # 校验参数
        # 保存注册数据：是注册业务的核心
        # 响应结果
        username = request.POST.get('username')
        password = request.POST.get('password')
        repassword = request.POST.get('repassword')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')

        if not all([username, password, repassword, mobile, allow]):
            return HttpResponseForbidden("请填写完整")

        if not re.match(r"^[a-zA-Z0-9_]{5,20}$", username):
            return HttpResponseForbidden("用户名不正确")

        if not re.match(r"[a-zA-Z0-9-_]{5,20}$", password):
            return HttpResponseForbidden("密码位数不正确")

        if password != repassword:
            return HttpResponseForbidden("两次输入的密码不匹配")

        if not re.match(r"^[1-9][0-9]{10}$", mobile):
            return HttpResponseForbidden("电话格式不正确")

        if allow != "on":
            return HttpResponseForbidden("请勾选协议")

        User.objects.create_user(username=username, password=password, mobile=mobile)
        
        return HttpResponse("OK")
        